/*
 * Copyright 2009 Red Hat, Inc.
 *
 * Red Hat licenses this file to you under the Apache License, version 2.0
 * (the "License"); you may not use this file except in compliance with the
 * License.  You may obtain a copy of the License at:
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package cn.xuyun.cc.tcp;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import cn.xuyun.cc.tcp.util.LogUtil;
import cn.xuyun.cc.tcp.vo.Constants;
import cn.xuyun.cc.tcp.vo.Entity;

/**
 * Handles a server-side channel.
 *
 * @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
 * @author <a href="http://gleamynode.net/">Trustin Lee</a>
 *
 * @version $Rev: 2121 $, $Date: 2010-02-02 09:38:07 +0900 (Tue, 02 Feb 2010) $
 */
public class TelnetServerHandler extends SimpleChannelUpstreamHandler {

	private static final Logger logger  = Logger.getLogger(TcpServerHandler.class);
	
	public static Channel channel=null;

	
	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		// TODO Auto-generated method stub
		
		channel=null;
		
		
		super.channelClosed(ctx, e);
		
		
	}
	

    @Override
    public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) {

        // Cast to a String first.
        // We know it is a String because we put some codec in TelnetPipelineFactory.
        String request = (String) e.getMessage();

        // Generate and write a response.
        StringBuilder sb=new StringBuilder();
        boolean close = false;
        if (request.length() == 0) {
            sb.append("Please type something.\r\n");
        } else if (request.toLowerCase().equals("exit")||request.toLowerCase().equals("quit")) {
            sb.append("bye bye!\r\n");
            close = true;
        } else {
        	
        	int k=request.indexOf(" ");
        	
        	String cmd=k>-1?request.substring(0,k):request;
        	String para=k>-1?request.substring(k+1).trim():"";
        	Integer code=Constants.cmdCode.get(cmd.toUpperCase());
        	if(code!=null)
        	{
        		channel=e.getChannel();
        		Entity entity=new Entity((int)(System.currentTimeMillis()/1000),1,0,0,code,para.getBytes(),0);
        		
        	}else{
        		sb.append("wrong command!\r\n");
        	}
        }

        // We do not need to write a ChannelBuffer here.
        // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
        ChannelFuture future = e.getChannel().write(sb.toString());

        // Close the connection after sending 'Have a good day!'
        // if the client has sent 'bye'.
        if (close) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();
        e.getChannel().close();
    }
}
